﻿using System;
using System.IO;
using System.Runtime.Serialization;
using System.Text;
using System.Xml.Serialization;
using Newtonsoft.Json;

namespace SaiLing.SingleSignOn.Repository
{
    public class ProjectEntitySetting
    {
        #region static
        [XmlIgnore]
        private static ProjectEntitySetting _instance;
        static ProjectEntitySetting()
        {
            string settingFile = GetSettingFile();
            if (File.Exists(settingFile))
            {
                var connectstring = File.ReadAllText(settingFile);
                _instance = JsonConvert.DeserializeObject<ProjectEntitySetting>(connectstring);
            }
            else
            {
                _instance = new ProjectEntitySetting
                {
                    ConnectionString = "Data Source=.;User ID=sa;Password=123456;Initial Catalog=SaiLing_Project_SSO;MultipleActiveResultSets=true;",
                    ProviderInvariantName = "System.Data.SqlClient",
                    ProviderManifestToken = "2012",
                };
                Save(_instance);
            }
        }

        private static void Save(ProjectEntitySetting instance)
        {
            var settingFile = GetSettingFile();
            var config = JsonConvert.SerializeObject(instance);
            File.WriteAllText(settingFile, config, Encoding.Default);
        }
        private static string GetSettingFile()
        {
            return Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "SaiLing.project.config");
        }
        public static ProjectEntitySetting Instance
        {
            get => _instance;
            set
            {
                _instance = value;
                Save(_instance);
            }
        }
        #endregion

        [DataMember]
        public string ConnectionString { get; set; }
        [DataMember]
        public string ProviderInvariantName { get; set; }
        [DataMember]
        public string ProviderManifestToken { get; set; }
    }
}
